<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商品管理
 */
namespace app\allwin\controller;
use app\allwin\model\AllwinShop;
use app\allwin\model\AllwinShopCate;
use app\allwin\model\AllwinShopCoupon;
use app\allwin\model\Coupon as CouponModel;
use app\allwin\model\AllwinStore;
use app\allwin\model\Coupon;

class Shop extends Common{

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'优选宝贝','url'=>url("allwin/shop/index")]]);
    }

    /**
     * 列表
     */
    public function index(){
        $condition = [];
        $status   = $this->request->param('status');
        switch ($status) {
            case 'trash':       //回收站
                $condition[] = ['is_del','=',1];
                break; 
            case 'off_sale': //在售
                $condition[] = ['is_sale','=',1];
                $condition[] = ['is_del','=',0];
                break;           
            case 'on_sale': //下架
                $condition[] = ['is_sale','=',0];
                $condition[] = ['is_del','=',0];
                break;  
            default:
                $condition[] = ['is_del','=',0];
                break;
        }
        $keyword  = $this->request->param('keyword');
        if(!empty($keyword)){
            $condition[] = ["name","like","%{$keyword}%"];
        }
        $cate_id  = $this->request->param('cate_id/d',0);
        if($cate_id){
            $condition[] = ["category_id","=",$cate_id];
        }        
        $view['lists']   = AllwinShop::where($this->mini_program)->where($condition)->order('id desc')->paginate(20,false,['query' => ['cate_id'=>$cate_id,'status' => $status,'keyword' => $keyword]]);
        $view['keyword'] = $keyword;
        $view['status']  = $status;
        $view['cate_id'] = $cate_id;
        $view['page']    = $this->request->param('page/d',0);
        return view()->assign($view);
    }

    /**
     * 添加
     */
    public function add(){
        if(request()->isAjax()){
            $param = [
                'category_id'       => $this->request->param('category_id/d'),
                'store_id'          => $this->request->param('store_id/d'),
                'types'             => $this->request->param('types/d', 0),
                'name'              => $this->request->param('name/s'),
                'title'             => $this->request->param('title/s'),
                'sell_price'        => $this->request->param('sell_price/f'),
                'market_price'      => $this->request->param('market_price/f', 0),
                'cost_price'        => $this->request->param('cost_price/f', 0),
                'warehouse_num'     => $this->request->param('warehouse_num/d', 0),
                'warehouse_sellnum' => $this->request->param('warehouse_sellnum/d', 0),
                'coupon_id'         => $this->request->param('coupon_id/d', 0),
                'vip_price'         => $this->request->param('vip_price/f', 0),
                'points'            => $this->request->param('points/d', 0),
                'unit'              => $this->request->param('unit/s'),
                'imgs'              => $this->request->param('imgs/a'),
                'img'               => $this->request->param('img/s'),
                'content'           => $this->request->param('content/s'),
                'group_title'       => $this->request->param('group_title/s'),
                'group_note'        => $this->request->param('group_note/s'),
                'group_img'         => $this->request->param('group_img/s'),
                'notice'            => $this->request->param('notice/s'),
                'detective_price'   => $this->request->param('detective_price/s'),
                'detective_uid'     => $this->request->param('detective_uid/s'),
                'share_price'       => $this->request->param('share_price/s'),
                'keyword'           => $this->request->param('keyword/s'),
                'end_time'          => $this->request->param('end_time/s'),
            ];
            $validate = $this->validate($param,'item.save');
            if(true !== $validate){
                return enjson(0,$validate);
            }
            if($param['detective_uid'] && empty($param['detective_price'])){
                return enjson(0,'经纪人所得必须填写');
            }
            $param['member_miniapp_id'] = $this->member_miniapp_id;
            $result =  AllwinShop::edit($param);
            if($result){
                return enjson(200,'操作成功',['url' => url('allwin/shop/index')]);
            }else{
                return enjson(0,'操作失败');
            }
        }else{
            $view['cate'] = AllwinShopCate::where($this->mini_program)->select();
            return view()->assign($view);
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        if(request()->isAjax()){
            $param = [
                'id'                => $this->request->param('id/d'),
                'store_id'          => $this->request->param('store_id/d'),
                'category_id'       => $this->request->param('category_id/d'),
                'types'             => $this->request->param('types/d', 0),
                'name'              => $this->request->param('name/s'),
                'title'             => $this->request->param('title/s'),
                'sell_price'        => $this->request->param('sell_price/f'),
                'market_price'      => $this->request->param('market_price/f', 0),
                'cost_price'        => $this->request->param('cost_price/f', 0),
                'warehouse_num'     => $this->request->param('warehouse_num/d', 0),
                'warehouse_sellnum' => $this->request->param('warehouse_sellnum/d', 0),
                'coupon_id'         => $this->request->param('coupon_id/d', 0),
                'vip_price'         => $this->request->param('vip_price/f', 0),
                'points'            => $this->request->param('points/d', 0),
                'imgs'              => $this->request->param('imgs/a'),
                'img'               => $this->request->param('img/s'),
                'content'           => $this->request->param('content/s'),
                'notice'            => $this->request->param('notice/s'),
                'detective_price'   => $this->request->param('detective_price/s'),
                'detective_uid'     => $this->request->param('detective_uid/d', 0),
                'share_price'       => $this->request->param('share_price/s'),
                'keyword'           => $this->request->param('keyword/s'),
                'group_title'       => $this->request->param('group_title/s'),
                'group_note'        => $this->request->param('group_note/s'),
                'group_img'         => $this->request->param('group_img/s'),
                'end_time'          => $this->request->param('end_time/s'),
            ];
            $validate = $this->validate($param,'item.save');
            if(true !== $validate){
                return enjson(0,$validate);
            }
            if($param['detective_uid'] && empty($param['detective_price'])){
                return enjson(0,'经纪人所得必须填写');
            }
            $result =  AllwinShop::edit($param);
            if($result){
                return enjson(200,'操作成功',['url' => url('allwin/shop/index')]);
            }else{
                return enjson(0,'操作失败');
            }
        }else{
            $view['id']     = $this->request->param('id/d');
            $view['info']   = AllwinShop::where(['id' => $view['id']])->find();
            $view['imgs']   = json_decode($view['info']['imgs'],true); 
            if(!empty($view['info']['store_id'])){
                $state = AllwinStore::where(['member_miniapp_id' => $this->member_miniapp_id,'id' => $view['info']['store_id']])->find();
                $view['storename'] = $state->name;
            }else{
                $view['storename'] = '请选择所属商家';
            }
            $view['cate'] = AllwinShopCate::where($this->mini_program)->select();
            return view()->assign($view);
        }
    }

     /**
     * 删除
     */
    public function delete(){
        $id  = $this->request->param('id/d',0);
        $ids = $this->request->param('ids/s');
        $result = AllwinShop::ids_delete($id,$ids);
        if($result){
            return enjson(200);
        }else{
            return enjson(403);
        } 
    }

    /**
     * 上架,下架,从回收站恢复
     */
    public function ids_action(){
        if(request()->isAjax()){
            $issale = $this->request->param('issale/d');
            $ids    = $this->request->param('ids/s');
            if(empty($ids)){
                return enjson(403,'没有选择任何要操作商品');
            }else{
                AllwinShop::ids_action($issale,$ids,$this->member_miniapp_id);
                return enjson(200);
            }
        }
    }
    
    /**
     * 商品栏目
     */
    public function category(){
        if(request()->isAjax()){
            $info = AllwinShopCate::where(['member_miniapp_id' => $this->member_miniapp_id,'parent_id' => $this->request->param('parent_id/d',0)])
                ->field('id,parent_id,title')
                ->order(['sort'=>'desc','id'=>'desc'])
                ->select();
            return enjson(200,'操作成功',$info);
        }else{
            $view['input'] = $this->request->param('input');
            $view['path']  = $this->request->param('path');
            return view('category',$view);
        }
    }
    
    /**
     *返回当前路径
     */
    public function category_path(){
        $info = AllwinShopCate::getPath($this->member_miniapp_id,$this->request->param('parent_id/d',0));
        if($info){
            $category = [];
            foreach ($info as $key => $value) {
                $category[] = $value['id'];
            }
            $category_id = implode(',',$category);
            return json(['code'=>200,'msg'=>'操作成功','data'=>$info,'category_id' => $category_id]);
        }
        return enjson(403,'读取商品分类路径失败');
    }

    /**
     * 计算价格
     */
    public function calculatePrice(){
        $coupon_id  = $this->request->param('coupon_id/d');
        $sell_price = $this->request->param('sell_price/f');
        $coupon = Coupon::where(['id' => $coupon_id])->find();
        if($coupon){
            if($coupon->types){
                $coupon_user_price = $sell_price - $sell_price * $coupon->discount/10; 
            }else{
                $coupon_user_price = $coupon->price;
            }
        }else{
            $coupon_user_price = 0;
        }
        return enjson(200,'成功',$coupon_user_price);
    }



    /**
     * 列表
     */
    public function coupon(int $id = 0){
        $view['lists']   = CouponModel::where($this->mini_program)->whereIn('id', AllwinShopCoupon::where($this->mini_program)->where(['shop_id' => $id])->column('coupon_id'))->order('is_platform desc,sort desc,is_lock desc,update_time desc')->paginate(10, false);
        $view['page']    = $this->request->param('page/d', 0);
        $view['shop_id'] = $id;
        return view()->assign($view);
    }


    /**
     * 优惠券选项
     */
    public function selectId(){
        $view['shop_id'] = $this->request->param('shop_id/d', 0);
        $view['keyword'] = $this->request->param('keyword');
        $view['lists']   = CouponModel::where($this->mini_program)->withSearch(['name'],['name' => $view['keyword']])->whereNotIn('id',AllwinShopCoupon::where($this->mini_program)->where(['shop_id' => $view['shop_id']])->column('coupon_id'))->order('is_top desc,sort desc,is_lock desc,update_time desc')->paginate(10,false);
        return view()->assign($view);
    }

    public function setId(){
        $shop_id   = $this->request->param('shop_id/d');
        $coupon_id = $this->request->param('coupon_id/d');
        AllwinShopCoupon::create(['shop_id' => $shop_id,'coupon_id' => $coupon_id,'member_miniapp_id' =>$this->member_miniapp_id,'create_time' => time()]);
        $this->redirect('coupon', ['id' => $shop_id]);
    }

    public function deleteShopCoupon(){
        $shop_id   = $this->request->param('shop_id/d');
        $coupon_id = $this->request->param('coupon_id/d');
        $result = AllwinShopCoupon::where(['shop_id' => $shop_id,'coupon_id' => $coupon_id])->delete();
        if($result){
            return enjson(200);
        }else{
            return enjson(403);
        }
    }
}